package com.zzy.controller;

import com.zzy.Pojo.MyRest;
import com.zzy.Pojo.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

//拦截器实现类
public class MyInterceptor implements HandlerInterceptor
{
    @Resource
    RedisTemplate<String,String> redisTemplate;
    @Resource
    RestTemplate restTemplate;
    //执行前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        boolean b = false;
        Cookie[] cookies = request.getCookies();
        if(cookies!=null)
        {
            for (Cookie c:cookies)
            {
                if(c.getName().equals("cz"))
                {
                    //有cookie,验证一下cookie值
                    String value = c.getValue();
                    RestTemplate restTemplate = new RestTemplate();
                    String url="http://127.0.0.1:8080/sso/yzcookie";
                    String[] split = value.split("&");
                    User user = new User();
                    user.setUsername(split[0]);
                    user.setPassword(split[1]);
                    ResponseEntity<MyRest> myRest = restTemplate.postForEntity(url,user,MyRest.class);
                    MyRest body = myRest.getBody();
                    if(body.getCode()==200)
                    {
                        b=true;
                    }
                }
            }
        }
           if(b==false)
           {
               String url ="http://127.0.0.1:8080/sso/remember?fanhui=http://127.0.0.1:8888/mall/login";
               response.sendRedirect(url);
           }
        return b;
    }

    //执行后调用
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
    //全部执行完调用
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
